<template>
  <el-container>
    <category-aside @node-click="handleNodeClick" v-power="'system:category:lists'"></category-aside>
    <el-container class="is-vertical" v-if="!currentCategory">
      <el-empty style="margin-top: 250px;" :image-size="100" description="请单击左侧模板分类后操作"></el-empty>
    </el-container>
    <el-container class="is-vertical" v-else v-power="'system:template:lists'">
      <el-header style="height: 60px; line-height: 60px;">
        <el-descriptions style="width: 100%;" :column="3" border size="small">
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                模板分类标识
              </div>
            </template>
            {{ currentCategory.code }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                模板分类名称
              </div>
            </template>
            {{ currentCategory.name }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                模板分类状态
              </div>
            </template>
            <el-tag :type="currentCategory.enabled ? 'success' : 'danger'">
              {{ currentCategory.enabled ? '启用' : '停用' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-header>
      <jcx-search v-model:show-search="showSearch" :show-button="false" :query-form="queryParams"
                  :power="'system:template:lists'" @handle-reset-query="handleResetQuery" @handle-search="handleSearch">
        <el-col :span="8">
          <el-form-item label="模板名称" prop="name">
            <el-input placeholder="模板名称" clearable v-model="queryParams.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="启用状态" prop="enabled">
            <el-select placeholder="启用状态" clearable v-model="queryParams.enabled">
              <el-option key="1" label="启用" :value="true"></el-option>
              <el-option key="0" label="停用" :value="false"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="模板类型" prop="type">
            <el-select placeholder="模板类型" clearable v-model="queryParams.type">
              <el-option key="1" label="Java" value="Java"></el-option>
              <el-option key="1" label="Vue" value="Vue"></el-option>
              <el-option key="1" label="JavaScript" value="JavaScript"></el-option>
              <el-option key="1" label="SQL" value="SQL"></el-option>
              <el-option key="1" label="Xml" value="Xml"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </jcx-search>
      <el-header>
        <div class="left-panel">
          <div class="left-panel-search" v-if="showSearch">
            <el-button type="primary" plain icon="el-icon-search" @click="handleSearch"
                       v-power="'system:template:lists'"></el-button>
            <el-button type="info" plain icon="el-icon-refresh" @click="handleResetQuery"></el-button>
          </div>
        </div>
        <div class="right-panel">
          <jcx-table-bar :column-list="columnList" v-model:config="config" v-model:show-search="showSearch"
                         @query-table="getList"></jcx-table-bar>
        </div>
      </el-header>
      <el-main class="no-padding">
        <el-table style="width: 100%" ref="table" row-key="id" v-loading="loading" :data="dataList"
                  :stripe="config.stripe" :border="config.border" :size="config.size"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection"></el-table-column>
          <template v-for="(column, index) in columnList" :key="index">
            <el-table-column v-if="!column.hide" :label="column.label" :prop="column.prop" :align="column.align"
                             :width="column.width" :fixed="column.fixed">
              <template #default="scope">
                <jcx-render-column v-if="column.render" :scope="scope" :render="column.render"></jcx-render-column>
                <span v-else>{{ scope.row[column.prop] }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </el-main>
      <el-footer>
        <div class="jcx-table-page">
          <div class="jcx-table-do">
            <el-button type="info" plain @click="handleReset">重 置</el-button>
            <el-button type="primary" plain icon="el-icon-plus" @click="handleAddClick"></el-button>
            <el-button type="danger" plain icon="el-icon-delete" :disabled="multiple"
                       @click="handleDeleteClick" v-power="'system:template:del'"></el-button>
            <el-button type="warning" plain icon="el-icon-edit" :disabled="single" @click="handleEditClick"
                       v-powers="['system:template:info']"></el-button>
          </div>
          <div class="jcx-table-pagination">
            <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
                           :small="true" :page-sizes="[10, 20, 30, 40, 50]" v-model:currentPage="queryParams.pageNum"
                           v-model:page-size="queryParams.pageSize" @current-change="getList"
                           @update:page-size="getList"></el-pagination>
          </div>
        </div>
      </el-footer>
      <el-dialog destroy-on-close append-to-body :close-on-click-modal="false" width="1080px" :title="title"
                 v-model="open" @closed="handleCancel">
        <template-form ref="templateFormRef" :form="form"></template-form>
        <template #footer>
          <el-button plain :type="form.id ? 'warning' : 'primary'" :loading="saving" @click="handleSubmitForm"
                     v-power="form.id ? 'system:template:edit' : 'system:template:add'">{{ form.id ? '修 改' : '保 存' }}
          </el-button>
          <el-button plain type="info" @click="handleCancel">取 消</el-button>
        </template>
      </el-dialog>

      <el-dialog destroy-on-close append-to-body :close-on-click-modal="false" fullscreen width="1080px"
                 title="编辑模板内容"
                 v-model="open2" @closed="handleCancel2">
        <content-form ref="contentFormRef" :form="form"></content-form>
        <template #footer>
          <el-button plain type="primary" :loading="saving2" @click="handleSubmitForm2" v-power="'system:template:edit'">
            保 存
          </el-button>
          <el-button plain type="info" @click="handleCancel2">取 消</el-button>
        </template>
      </el-dialog>

    </el-container>
  </el-container>
</template>

<script setup>
import categoryAside from "./aside.vue";
import templateForm from "./template.vue";
import contentForm from "./content.vue";
import {ref} from "vue";
import templateApi from "@/api/generator/template";
import renderUtil from "@/utils/render";
import modal from "@/utils/modal";

const currentCategory = ref(null);

const handleNodeClick = (data) => {
  currentCategory.value = data;
  queryParams.value.categoryId = data.id;
  getList();
}

const handleReset = () => {
  currentCategory.value = null;
}

// 是否显示搜索栏
const showSearch = ref(true);
// 查询条件
const queryParams = ref({
  categoryId: null,
  name: null,
  enabled: null,
  pageNum: 1,
  pageSize: 10
});
// 分页总条数
const total = ref(0);
// 表格模板
const config = ref({
  // 表格大小
  size: "default",
  // 表格边框
  border: true,
  // 表格斑马图纹
  stripe: true
});
// 表格数据列表
const dataList = ref([]);
// 表格列数据
const columnList = ref([
  {
    label: '模板标识',
    prop: 'code',
    hide: false,
    align: 'center'
  },
  {
    label: '模板名称',
    prop: 'name',
    hide: false,
    align: 'center'
  },
  {
    label: '模板类型',
    prop: 'type',
    hide: false,
    align: 'center',
    render: (h, row) => {
      return renderUtil.renderTemplateType(row.type);
    }
  },
  {
    label: '是否启用',
    prop: 'enabled',
    hide: false,
    align: 'center',
    render: (h, row) => {
      return renderUtil.renderYesOrNo(row.enabled, '启用', '停用');
    }
  },
  {
    label: '排序',
    prop: 'sort',
    hide: false,
    align: 'center'
  },
  {
    label: '创建时间',
    prop: 'createTime',
    hide: false,
    align: 'center'
  },
  {
    label: '备注',
    prop: 'remark',
    hide: false,
    align: 'center'
  },
  {
    label: '操作',
    width: '175px',
    prop: 'operation',
    hide: false,
    align: 'center',
    render: (h, row) => {
      return renderUtil.renderThreeOperation(row, handleDeleteClick, 'system:template:del', handleEditClick, ['system:template:info'], handleContentClick, ['system:template:info']);
    }
  }
]);
// 表格中被选中的数据列表
const selectList = ref([]);

// 加载动画
const loading = ref(false);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 表单组件
const templateFormRef = ref(null);
// 保存状态
const saving = ref(false);
// 弹出层状态
const open = ref(false);
// 弹出层标题
const title = ref('新增模板');
// 表单数据
const form = ref({
  id: null,
  code: null,
  name: null,
  type: null,
  content: null,
  sort: null,
  remark: null,
  enabled: null,
  categoryIdList: [],
});

const open2 = ref(false);
const saving2 = ref(false);
const contentFormRef = ref(null);

// 查询按钮触发方法
const handleSearch = () => {
  getList();
}

// 重置查询条件触发按钮
const handleResetQuery = () => {
  queryParams.value.name = null;
  queryParams.value.enabled = null;
  queryParams.value.type = null;
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  handleSearch();
}

// 获取数据方法
const getList = () => {
  loading.value = true;
  templateApi.lists.get(queryParams.value).then(response => {
    dataList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  })
}

// 表格选中触发方法
const handleSelectionChange = (selection) => {
  selectList.value = selection.map(item => item);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 新增按钮方法
const handleAddClick = () => {
  title.value = '新增模板';
  open.value = true;
}

// 删除按钮方法
const handleDeleteClick = (row) => {
  const idList = row.id ? [row.id] : selectList.value.map(item => item.id);
  modal.confirm(`确定删除选中的 ${idList.length} 项吗？`).then(() => {
    templateApi.del.delete(idList).then(response => {
      if (response.status) {
        modal.successMessage(response.message);
        getList();
      } else {
        modal.errorMessage(response.message);
      }
    });
  }).catch(() => {
    modal.infoMessage("用户取消操作");
  })
}

// 编辑按钮方法
const handleEditClick = (row) => {
  const id = row.id || selectList.value[0].id;
  templateApi.info.get(id, true).then(response => {
    form.value = response.data;
    title.value = '编辑模板';
    open.value = true;
  });
}

// 重置 form
const resetForm = (formEl) => {
  form.value = {
    id: null,
    code: null,
    name: null,
    type: null,
    content: null,
    sort: null,
    remark: null,
    enabled: null,
    categoryIdList: [],
  };
  if (!formEl) return;
  formEl.resetFields();
}

// 关闭弹窗
const handleCancel = () => {
  resetForm(templateFormRef.value.getFormRef());
  open.value = false;
}

// 弹窗提交
const handleSubmitForm = () => {
  saving.value = true;
  const formRef = templateFormRef.value.getFormRef();
  formRef.validate(valid => {
    if (valid) {
      if (form.value.id) {
        // 修改
        templateApi.edit.put(form.value).then(response => {
          modal.message(response.message, {type: response.status ? 'success' : 'error'})
          saving.value = false;
          if (response.status) {
            handleCancel();
            handleSearch();
          }
        })
      } else {
        // 新增
        templateApi.add.post(form.value).then(response => {
          modal.message(response.message, {type: response.status ? 'success' : 'error'})
          saving.value = false;
          if (response.status) {
            handleCancel();
            handleSearch();
          }
        })
      }
    } else {
      saving.value = false;
      modal.warningMessage("表单校验不通过");
    }
  });
}

const handleContentClick = (row) => {
  const id = row.id || selectList.value[0].id;
  templateApi.info.get(id, true).then(response => {
    form.value = response.data;
    open2.value = true;
  });
}

// 关闭弹窗
const handleCancel2 = () => {
  resetForm(contentFormRef.value.getFormRef());
  open2.value = false;
}

// 弹窗提交
const handleSubmitForm2 = () => {
  if (!form.value.id) {
    modal.errorMessage("未选择有效模板");
  }
  saving2.value = true;
  const formRef = contentFormRef.value.getFormRef();
  formRef.validate(valid => {
    if (valid) {
      // 修改
      templateApi.edit.put(form.value).then(response => {
        modal.message(response.message, {type: response.status ? 'success' : 'error'})
        saving2.value = false;
        if (response.status) {
          handleCancel2();
          handleSearch();
        }
      })
    } else {
      saving2.value = false;
    }
  });
}
</script>

<style scoped lang="scss">
</style>
